//
//  SearchViewController.m
//  Topit
//
//  Created by dllo on 15/11/27.
//  Copyright © 2015年 YXY. All rights reserved.
//

#import "SearchViewController.h"
#import "YXYSelectionViewController.h"
#import "YXYSearchWebViewController.h"
#import "YXYSkipViewController.h"
#import "YXYSearchPaperCollectionViewCell.h"
#import "YXYWallImageModel.h"
#import "YXYWallPaperModel.h"
#import "MJRefresh.h"
#import "DWBubbleMenuButton.h"
@interface SearchViewController ()<UICollectionViewDataSource, UICollectionViewDelegate, SearchSkipDelegate>
@property (nonatomic, retain) UICollectionView *collectionView;
@property (nonatomic, retain) NSMutableArray *wallArray;
@property (nonatomic, retain) NSMutableArray *itemArray;
@property (nonatomic, assign) int number;
@property (nonatomic, retain) NSString *URl;
@property (nonatomic, retain) NSMutableArray *urlArray;

@end

@implementation SearchViewController

- (void)dealloc {
    [_itemArray release];
    [_collectionView release];
    [_wallArray release];
    [super dealloc];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"发现";
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.urlArray = [NSMutableArray arrayWithObjects:kWallPaperURL, kIkonURL, kFoodURl, kFashion, kShootURL, nil];
    
    UILabel *homeLabel = [self createHomeButtonView];
    DWBubbleMenuButton *downMenuButton = [[DWBubbleMenuButton alloc] initWithFrame:CGRectMake(20.f, 20.f, homeLabel.frame.size.width, homeLabel.frame.size.height) expansionDirection:DirectionRight];
    
    downMenuButton.homeButtonView = homeLabel;
    
    downMenuButton.collapseAfterSelection = NO;
    
    [downMenuButton addButtons:[self createDemoButtonArray]];
    
    self.URl = kWallPaperURL;
    
    [self setUpCollectionView];
    [self getDate];
    [self getFootRefresh];
    [self.collectionView addSubview:downMenuButton];
    // Do any additional setup after loading the view.
}

-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:YES];
    [self.collectionView nightMode];
    [self.collectionView reloadData];
}

#pragma mark - 创建根目录 
- (UILabel *)createHomeButtonView {
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 40, 40)];
    label.text = @"菜单";
    label.textColor = [UIColor whiteColor];
    [label setFont:[UIFont systemFontOfSize:15]];
    label.textAlignment = 1;
    label.layer.cornerRadius = label.frame.size.height / 2.f;
    label.backgroundColor =[UIColor colorWithRed:0.f green:0.f blue:0.f alpha:0.5f];
    label.clipsToBounds = YES;
    return label;
}
#pragma mark - 创建button子按钮
- (NSArray *)createDemoButtonArray {
    NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:0];
    int i = 0;
    for (NSString *title in @[@"壁纸", @"插画", @"美食", @"时尚", @"摄影"]) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
        
        [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [button setTitle:title forState:UIControlStateNormal];
        button.titleLabel.font = [UIFont systemFontOfSize:12];
        button.frame = CGRectMake(0.f, 0.f, 30.f, 30.f);
        button.layer.cornerRadius = button.frame.size.height / 2.f;
        button.backgroundColor = [UIColor colorWithRed:0.f green:0.f blue:0.f alpha:0.5f];
        button.clipsToBounds = YES;
        button.tag = i++;
        
        [button addTarget:self action:@selector(test:) forControlEvents:UIControlEventTouchUpInside];
        
        [buttons addObject:button];
    }
    return [buttons copy];
}

- (void)test:(UIButton *)sender {
    self.URl = self.urlArray[sender.tag];
    [self getDate];
    [self getFootRefresh];
    [self.collectionView reloadData];
}
#pragma mark - 网络请求
- (void)getDate {
    
    self.wallArray = [NSMutableArray arrayWithCapacity:0];
    self.itemArray = [NSMutableArray arrayWithCapacity:0];
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.labelText = @"正在加载";
    hud.mode = MBProgressHUDModeIndeterminate;
    [YXYNetWorkTool getWithUrl:self.URl parameter:nil httpHeader:nil responseType:ResponseTypeJSON success:^(id result) {
        for (NSDictionary *dic in result[@"info"][@"category"]) {
            NSArray *array = dic[@"item"];
            if (array.count) {
                YXYWallPaperModel *wallPaperModel = [[YXYWallPaperModel alloc] initWithDictionary:dic];
                if ([wallPaperModel.name isEqualToString:@"精选集"]) {
                    for (int i = 0; i < wallPaperModel.itemArray.count; i++) {
                        [_wallArray addObject:wallPaperModel.itemArray[i]];
                    }
                }else if ([wallPaperModel.name isEqualToString:@"壁纸达人"]) {
                    for (int i = 0; i < wallPaperModel.itemArray.count; i++) {
                        [_wallArray addObject:wallPaperModel.itemArray[i]];
                    }
                }else if ([wallPaperModel.name isEqualToString:@"热门活动"]) {
                    for (int i = 0; i < wallPaperModel.itemArray.count; i++) {
                        [_wallArray addObject:wallPaperModel.itemArray[i]];
                    }
                }
                [wallPaperModel release];
            }
        }
        for (NSDictionary *dic in result[@"item"]) {
            YXYWallImageModel *wallImageModel = [[YXYWallImageModel alloc] initWithDictionary:dic];
            [self.itemArray addObject:wallImageModel];
            [wallImageModel release];
            
            
        }
        hud.hidden = YES;
        dispatch_async(dispatch_get_main_queue(), ^{
            [_collectionView reloadData];
        });
    } fail:^(NSError *error) {
        [hud hide:YES];
        [ProgressHUD showError:@"请检查网络"];
    }];
    
}
-(void)getFootRefresh {
    
    [self.collectionView addFooterWithCallback:^{
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        hud.labelText = @"正在加载";
        hud.mode = MBProgressHUDModeIndeterminate;
        self.number += 30;
        NSString *num = [NSString stringWithFormat:@"%d", _number];
        NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:num, @"offset", nil];
        [YXYNetWorkTool getWithUrl:self.URl parameter:dic httpHeader:nil responseType:ResponseTypeJSON success:^(id result) {
            if ([result[@"item"] isKindOfClass:[NSArray class]]) {
                for (NSDictionary *dic in result[@"item"]) {
                    YXYWallImageModel *wallImageModel = [[YXYWallImageModel alloc] initWithDictionary:dic];
                    [self.itemArray addObject:wallImageModel];
                    [wallImageModel release];
                }
            }else {
                UIAlertController *alertView = [UIAlertController alertControllerWithTitle:@"亲爱的" message:@"已经到底er了" preferredStyle:UIAlertControllerStyleAlert];
                [alertView addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    
                }]];
                [self presentViewController:alertView animated:YES completion:nil];
            }
            [hud hide:YES];
            dispatch_async(dispatch_get_main_queue(), ^{
                [_collectionView reloadData];
                [_collectionView footerEndRefreshing];
            });
        } fail:^(NSError *error) {
            [hud hide:YES];
            [ProgressHUD showError:@"请检查网络"];
        }];
    }];
}


#pragma mark - collectionView

- (void)setUpCollectionView {
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.itemSize = CGSizeMake(self.view.frame.size.width / 3, self.view.frame.size.height / 5);
    flowLayout.minimumInteritemSpacing = 0;
    flowLayout.minimumLineSpacing = 0;
    [flowLayout setHeaderReferenceSize:CGSizeMake(self.view.frame.size.width, self.view.frame.size.height)];
    
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height) collectionViewLayout:flowLayout];
    _collectionView.backgroundColor = [UIColor whiteColor];
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    [_collectionView registerClass:[YXYSearchPaperCollectionViewCell class] forCellWithReuseIdentifier:@"YXYSearchPaperCollectionViewCellIdentifier"];
    [_collectionView registerClass:[SearchHeadView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"SearchHeadView"];
    [self.view addSubview:_collectionView];
    [flowLayout release];
    [_collectionView release];
    
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.itemArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    YXYSearchPaperCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"YXYSearchPaperCollectionViewCellIdentifier" forIndexPath:indexPath];
    YXYWallImageModel *wallImageModel = self.itemArray[indexPath.item];
    [cell.images sd_setImageWithURL:wallImageModel.icon[@"url"]];
    return cell;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    UICollectionReusableView *reusableView = nil;
    if (kind == UICollectionElementKindSectionHeader) {
        SearchHeadView *searchHeadView = (SearchHeadView *)[collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"SearchHeadView" forIndexPath:indexPath];
        [searchHeadView.collectionView reloadData];
        searchHeadView.delegate = self;
        [searchHeadView setDataSource:self.wallArray];
        reusableView = searchHeadView;
    }
    return reusableView;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    YXYWallImageModel *wallImageModel = self.itemArray[indexPath.item];
    YXYSkipViewController *skipVC = [[YXYSkipViewController alloc] initWithURL:wallImageModel.next];
    skipVC.view.backgroundColor = [UIColor whiteColor];
    [self.navigationController pushViewController:skipVC animated:YES];
    [skipVC release];
}

#pragma mark 跳转
- (void)searchSkipDelegate:(NSString *)url {
    YXYSelectionViewController *selectionVC = [[YXYSelectionViewController alloc] initWithURL:url];
    [self.navigationController pushViewController:selectionVC animated:YES];
    [selectionVC release];
}

- (void)searchReadSkipDelegate:(NSString *)url {
    YXYSearchWebViewController *searchWebVC = [[YXYSearchWebViewController alloc] init];
    searchWebVC.url = url;
    [self.navigationController pushViewController:searchWebVC animated:YES];
    [searchWebVC release];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//- (BOOL)prefersStatusBarHidden {
//    return true;
//}
/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
